/**
 * 安全奖i订单 编辑页
 *
 * 作者 zhangwei
 * 日期 2024-09-02 11:28:06
 */
layui.use(['jquery', 'febs', 'form', 'validate', 'table', 'commonJS', 'autocomplete'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        tableIns,
        $view = $('#incentiveGoodsOrder-edit'),
        $addUserBtn = $view.find("#addUserBtn"),
        $addGoodsBtn = $view.find("#addGoodsBtn"),
        incentiveGoodsOrderDto = {
            user: {},
            goodsList: []
        }

    validate = layui.validate;
    var tenantId = POPUP_DATA.tenantId;
    var goodsList = [];
    var selectUser;
    var calcList = [];
    var totalScore = 0;
    var lastScore; // 剩余积分

    form.verify(validate);
    form.render();
    initFormValue();

    function initFormValue() {
        if (incentiveGoodsOrderData) {
            form.val("incentiveGoodsOrder-edit-form", {
                "goodsOrderId": incentiveGoodsOrderData.goodsOrderId,
                "tenantId": incentiveGoodsOrderData.tenantId,
                "goodsOrderType": incentiveGoodsOrderData.goodsOrderType,
                "rewardApplyId": incentiveGoodsOrderData.rewardApplyId,
                "orderNo": incentiveGoodsOrderData.orderNo,
                "orderDate": incentiveGoodsOrderData.orderDate,
                "orderScore": incentiveGoodsOrderData.orderScore,
                "exchangeCode": incentiveGoodsOrderData.exchangeCode,
                "exchangeDate": incentiveGoodsOrderData.exchangeDate,
                "status": incentiveGoodsOrderData.status,
            });
        }
    }

    form.on('submit(incentiveGoodsOrder-edit-form-submit)', function (data) {
        addOrUpdate(data.field);
        return false;
    });

    function getTenantId() {
        if (incentiveGoodsOrderData) {
            return incentiveGoodsOrderData.tenantId;
        } else {
            return POPUP_DATA.tenantId;
        }
    }

    window.inputChange = function (value) {
        if (value === "") {
            selectUser = {};
            $view.find("#info").addClass("febs-hide")
            tableIns.reload({data: []})
            $addGoodsBtn.addClass("layui-disabled").attr("disabled", true).attr("title", "请先选择人员")
        }
    }

    function initInfo(data) {
        $view.find("#userNo").text(data.userNo)
        $view.find("#deptName").text(data.deptName)
        $view.find("#score").text(commonJS.isEmpty(data.totalScore) ? '0' : data.totalScore);
        $view.find("#info").removeClass("febs-hide")
    }

    $view.find('#scanInput').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName: 'keywords',
        useType: 'user',
        params: {tenantId: getTenantId()},
        onSelect: function (suggestion) {
            selectUser = suggestion
            lastScore = suggestion.totalScore; // 初始剩余积分
            initInfo(suggestion)
            removeBtnDisabled()
        },
    });

    function removeBtnDisabled() {
        $addGoodsBtn.removeClass("layui-disabled").removeAttr("disabled").removeAttr("title")
    }

    $addUserBtn.on('click', function () {
        febs.modal.open('选择用户', 'common/user', {
            btn: ['确认', '关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%'] : ['90%', '85%'],
            data: {
                tenantId: getTenantId(),
                multiple: false,
            },
            yes: function (index, layero) {
                let selectData = null
                if (typeof getSelectData === 'function') {
                    selectData = getSelectData()
                }
                if (selectData) {
                    selectUser = selectData
                    $view.find("input[name='scanInput']").val(selectData.userName)
                    initInfo(selectData);
                    removeBtnDisabled();
                    lastScore = selectData.totalScore; // 初始剩余积分
                    layer.close(index);
                }

            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });


    $addGoodsBtn.on('click', function () {
        febs.modal.open('奖品选择', 'common/goods', {
            btn: ['确认', '关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%'] : ['80%', '85%'],
            data: {
                tenantId: tenantId,
                selectList: goodsList,
                multiple: true,
            },
            yes: function (index, layero) {
                let selectData = null
                if (typeof getSelectData === 'function') {
                    selectData = getSelectData()
                }
                if (selectData) {
                    for (var i = 0; i < selectData.length; i++) {
                        var score = $view.find("#score").text()
                        if (commonJS.isEmpty(selectUser)) {
                            febs.alert.warn("请先选择兑现用户!");
                            return false;
                        }
                        if (selectData[i].inventory <= 0) {
                            febs.alert.warn("奖品【" + selectData[i].goodsName + "】库存不足无法兑现!");
                            return false;
                        }
                        if (score < selectData[i].exchangeScore) {
                            febs.alert.warn("奖品【" + selectData[i].goodsName + "】用户积分不足请确认!");
                            return false;
                        }
                        lastScore -= selectData[i].exchangeScore;
                        if (lastScore < 0) {
                            febs.alert.warn("奖品【" + selectData[i].goodsName + "】用户积分不足无法选择该奖品!");
                            return false;
                        }
                        var temp = {};
                        temp.goodsId = selectData[i].goodsId;
                        temp.smallPath = selectData[i].smallPath;
                        temp.filePath = selectData[i].smallPath;
                        temp.goodsImage = selectData[i].smallPath;
                        temp.goodsName = selectData[i].goodsName;
                        temp.goodsNumber = 1; // 默认一个数量
                        temp.goodsPrice = selectData[i].goodsPrice;
                        temp.inventory = selectData[i].inventory;
                        temp.goodsUnit = selectData[i].goodsUnit;
                        temp.tenantId = selectData[i].tenantId;
                        temp.exchangeScore = selectData[i].exchangeScore;
                        if (isRepeat(goodsList, selectData[i].goodsId)) {
                            febs.alert.warn("奖品" + selectData[i].goodsName + "已添加!");
                            return false;
                        }
                        totalScore += selectData[i].exchangeScore;
                        goodsList.push(temp);
                    }
                }
                reloadTab(goodsList);
                // dynamicCalcNumber(goodsList)
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    // 监听表格单元格编辑事件
    table.on('edit(goodsTable)', function (obj) {
        var userScore = selectUser.totalScore
        let data = obj.data;
        let reg = /^(0|[1-9]\d*)$/;
        let filter = goodsList.filter(item => item.goodsId === data.goodsId);
        if (filter && filter.length > 0) {
            let currentItem = filter[0];
            // 计算当前剩余积分最多能兑换的数量
            // let maxGoodsNumber = currentItem.editFlg ? Math.floor(lastScore / currentItem.exchangeScore) : Math.floor((lastScore + currentItem.exchangeScore) / currentItem.exchangeScore);
            if (!reg.test(data.goodsNumber)) {
                febs.alert.warn("请输入一个正整数!");
                filter[0].goodsNumber = 1
                reloadTab(goodsList);
                return false;
            }
            let total = 0;
            var dataList = layui.table.cache['goodsTable'];
            for (let i = 0; i < dataList.length; i++) {
                total += dataList[i].goodsNumber * dataList[i].exchangeScore;
            }
            if (total > userScore) {
                febs.alert.warn("【" + currentItem.goodsName + "】数量超过该用户可兑换最大数量!");
                // 重置为最大可兑换数量
                currentItem.goodsNumber = 1;
                reloadTab(goodsList);
                return false;
            }
        }
    });


    initTable();

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'goodsTable',
            page: false,
            limit: Number.MAX_VALUE,
            // url: ctx + 'incentiveGoodsOrder/list',
            data: goodsList,
            // height: getTableHeight(),
            skin: '',
            cols: [[
                {type: 'numbers', title: '序号'},
                {field: 'goodsName', title: '奖品名称', minWidth: 120},
                {field: 'inventory', title: '在库数量', width: 90, align: "center"},
                {field: 'exchangeScore', title: '兑换积分', width: 90, align: "center"},
                {field: 'goodsNumber', title: '奖品数量', edit: 'text',align: "center", width: 150},
                {title: '操作', toolbar: '#goods-option', align: 'center', width: 60, fixed: 'right'}
            ]],
            defaultToolbar: []
        });
    }

    table.on('tool(goodsTable)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                let score = data.goodsNumber * data.exchangeScore;
                totalScore -= score;
                let goodsIndex = goodsList.findIndex(item => item.goodsId === data.goodsId)
                if (goodsIndex !== -1) {
                    goodsList.splice(goodsIndex, 1);
                }
                // var cacheData = layui.table.cache['goodsTable'];//获取缓存
                // obj.del();//①移除这一行
                // var rowIndex = obj.tr.attr("data-index"); //获取行索引
                // cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                // goodsList = cacheData;
                reloadTab(goodsList);

                layer.close(index);//关闭弹窗
            });
        }
    });

    function reloadTab(data) {
        tableIns.reload({data: data});
    }

    function isRepeat(arr, goodsId) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]['goodsId'] === goodsId) {
                return true;
            }
        }
        return false;
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $view.find("#scanIcon").on('click', function () {
        alert(1)
        // TODO 扫描用户编号
    })

    function addOrUpdate(data) {
        if (commonJS.isEmpty(selectUser)) {
            febs.alert.warn('未选择用户');
            return false;
        }
        var cacheData = layui.table.cache['goodsTable'];
        if (!cacheData.length) {
            febs.alert.warn('未选择奖品');
            return false;
        }
        let flg;
        let temp;
        let reg = /^(0|[1-9]\d*)$/;
        for (let i = 0; i < cacheData.length; i++) {
            if (commonJS.isEmpty(cacheData[i].goodsNumber)) {
                temp = cacheData[i];
                flg = "1";
                break;
            } else {
                if (cacheData[i].goodsNumber > cacheData[i].inventory) {
                    temp = cacheData[i];
                    flg = "2";
                    break;
                }
            }
            if (!reg.test(cacheData[i].goodsNumber)) {
                temp = cacheData[i];
                flg = "3";
                break;
            }
        }
        if (flg === "1") {
            febs.alert.warn("【" + temp.goodsName + '】未设置奖品数量');
            return false
        } else if (flg === "2") {
            febs.alert.warn("【" + temp.goodsName + '】奖品数量超过在库数量');
            return false
        } else if (flg === "3") {
            febs.alert.warn("【" + temp.goodsName + '】奖品数量请设置为正整数');
            return false
        }
        incentiveGoodsOrderDto.user = selectUser;
        incentiveGoodsOrderDto.goodsList = cacheData
        incentiveGoodsOrderDto.tenantId = tenantId
        incentiveGoodsOrderDto.goodsOrderType = "3"

        febs.modal.confirm("保存提示！", "是否兑现？", function (index) {
            if (data.goodsOrderId && data.goodsOrderId.length > 0) {
                febs.postArray(ctx + 'incentiveGoodsOrder/update', incentiveGoodsOrderDto, function () {
                    layer.closeAll();
                    febs.alert.success('兑现成功');
                    febs.reloadPage();
                });
            } else {
                febs.postArray(ctx + 'incentiveGoodsOrder', incentiveGoodsOrderDto, function () {
                    layer.closeAll();
                    febs.alert.success('兑现成功');
                    $('#febs-incentiveGoodsOrder').find('#query').trigger('click');
                });
            }
        })
    }
});